package com.yanmk.order.service.impl;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import com.yanmk.order.bean.Order;
import com.yanmk.order.service.OrderService;
import com.yanmk.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @program: cloud-demo
 * @description:
 * @author: Mr.Yan
 * @create: 2025-02-04 16:50
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
@Autowired
 DiscoveryClient discoveryClient;
@Autowired
RestTemplate restTemplate;
@Autowired
LoadBalancerClient loadBalancerClient;

@Override
public Order createOrder(Long productId, Long userId) {
 Order order = new Order();
 Product product = getProductByLoadBalance(productId);
 BigDecimal multiply = product.getPrice().multiply(new BigDecimal(product.getNum()));

 order.setId(1L);
// 计算的金额应该是根据商品的价格和数量计算出来的
 order.setTotalAmount(multiply);
 order.setUserId(userId);
 order.setNickName("张三");
 order.setAddress("山东省青岛市市北区");
//TODO: 这里应该是根据productId远程查询商品信息，然后设置到order中
 order.setProductList(Arrays.asList(product));
 return order;
}
//3.这是有负载均衡的调用方式----------基于注解方式
private Product getProductByLoadBalance(Long productId) {
 // TODO: 这里应该是远程调用product-service的接口，查询productId对应的商品信息
// 格式   http://服务名/接口名/参数
String url = "http://services-product/product/"+productId;
 log.info("product url: "+url);
// service-product 会被动态替换  http://192.168.47.1:9001/product/100
// 2.远程发送请求，获取商品信息
 Product product = restTemplate.getForObject(url, Product.class);
 return product;
}

//2.这是有负载均衡的调用方式------------------------基于spring-cloud-loadbalancer
//private Product getProductByLoadBalance(Long productId) {
// // TODO: 这里应该是远程调用product-service的接口，查询productId对应的商品信息
// ServiceInstance choose = loadBalancerClient.choose("services-product");
// String url = "http://"+choose.getHost()+":"+choose.getPort()+"/product/"+productId;
// log.info("product url: "+url);
//// 2.远程发送请求，获取商品信息
// Product product = restTemplate.getForObject(url, Product.class);
// return product;
//}

//1.这是没有负载均衡的调用方式----------
//private Product getProduct(Long productId) {
// // TODO: 这里应该是远程调用product-service的接口，查询productId对应的商品信息
// List<ServiceInstance> instances = discoveryClient.getInstances("services-product");
// ServiceInstance serviceInstance = instances.get(0);
// String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/product/"+productId;
// log.info("product url: "+url);
//// 2.远程发送请求，获取商品信息
// Product product = restTemplate.getForObject(url, Product.class);
// return product;
//}

}
